<template>
  <div class="update-box">
    <Top />
    <div class="sub-box">
      <van-field
        v-model="state.name"
        name="用户名"
        label="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field name="uploader" label="用户头像">
        <template #input>
          <van-uploader v-model="state.pic" multiple :max-count="1" />
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          @click="submit"
          :loading="state.loading"
          loading-text="修改中..."
        >
          修改信息
        </van-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { storeToRefs } from "pinia";
import {reactive } from "vue-demi";
import Top from "../components/Top.vue";
import { Toast } from "vant";
import "vant/es/toast/style";
import { useStore } from "../store/index";
import api from "../api";
import { useRouter } from "vue-router";
const store = useStore();
const router = useRouter()
console.log(store);
let { info } = store;
let { name } = info;
let state = reactive({
  name,
  pic: [],
  loading:false
});

const submit = async () => {
  if(state.loading) return
  let {name,pic} = state
  let reg = new RegExp("[\\u4E00-\\u9FFF]{3,6}$","g");
  if(!reg.test(name)){
    Toast("用户名格式错误\n(3-6位中文)")
    return
  }
  
  if(pic.length===0){
    Toast("必须上传一张图片")
    return
  }
  state.loading = true
  let {code,data} = await api.userUpdate(name,pic[0].file)
  if(+code!==0){
    Toast('修改失败')
    return
  }
  Toast("成功修改")
  store.changeInfo(data)
  router.back()
  state.loading = false
};
</script>

<style lang="less" scoped>
.update-box {
  height: 100vh;
  .sub-box {
    margin-top: 20px;
  }
}
</style>
